package rai.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import rai.dto.LoginUserDTO;
import rai.util.Constants;

/**
 * Database Operation for Login form.
 * @author Administrator
 */
public class LoginDAO {
    /** log property. */
    private static Logger log = Logger.getLogger("LoginDAO");

    /**
     * Get the information of one specify user.
     * @param ID
     * @param name
     * @param pass
     * @return
     */
    public LoginUserDTO getUser(final String name, final String pass) {
        LoginUserDTO Userdata = null;
        Connection conn = null;
        String query = Constants.BLANK_VALUE;
        ResultSet rs = null;
        PreparedStatement pStat = null;

        try {
            // query command
            query = "select * from user where UserName=? and Password=?";
            // get connection
            conn = rai.util.Connection.getConnection();
            // prepare statement
            pStat = conn.prepareStatement(query);
            pStat.setString(1, name);
            pStat.setString(2, pass);
            // execute query
            rs = pStat.executeQuery();
            // get result
            while (rs.next()) {
                Userdata = new LoginUserDTO();
                Userdata.setId(rs.getInt("EmpID"));
                Userdata.setUserName(rs.getString("UserName"));
                Userdata.setPassword(rs.getString("Password"));
                Userdata.setRole(rs.getString("Role"));
            }
        } catch (final Exception sqlEx) {
            log.error("LoginDAO.getUser " + sqlEx);
        } finally {
            try {
                rs.close();
                pStat.close();
                conn.close();
            } catch (final SQLException sqlEx) {
                log.error("LoginDAO.getUser " + sqlEx);
            }
        }
        return Userdata;
    }
}
